<template>
  <common-page :title="title ? '编辑日志资产' : '新增日志资产'">
    <div slot="header">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" @click="submit" :loading="loading"
        >保存
      </el-button>
    </div>
    <div slot="content" class="common-page-content">
      <el-form
        :model="form"
        ref="form"
        :inline="true"
        label-width="110px"
        :rules="rules"
        @submit.native.prevent
      >
        <common-group-title title="基本信息"></common-group-title>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产编码" prop="assetCode">
              <common-input
                clearable
                v-model="form.assetCode"
                placeholder="请输入"
                :maxlength="16"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产名称" prop="assetName">
              <common-input
                clearable
                v-model="form.assetName"
                placeholder="请输入"
                :maxlength="16"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类型名称" prop="categoryThirdCode">
              <!-- <treeselect
                :options="allDepList"
                placeholder="请选择"
                v-model="form.categoryThirdCode"
                @select="iscategoryThirdCode"
              /> -->
              <el-cascader
                style="width: 100%"
                v-model="form.categoryThirdCode"
                :options="allDepList"
                @change="handleChange"
                :props="categoryFirstCodeProps"
                :show-all-levels="false"
              >
                <template slot-scope="{ node, data }">
                  <common-marquee-text
                    :content="data.name"
                  ></common-marquee-text>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类型" prop="categoryFirstCode">
              <common-input
                :disabled="true"
                clearable
                v-model="categoryThirdName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="上级资产" prop="parentAsset" >
              <el-select
                placeholder="请选择"
                clearable
                v-model="form.parentAsset"
                style="width: calc(100%-90px)"
              >
                <el-option label="有负责人" :value="0"> </el-option>
                <el-option label="无负债" :value="1"> </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="厂家" prop="factory">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.factory"
              >
                <el-option
                  v-for="item in factoryList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作系统" prop="osVersion">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.osVersion"
              >
                <el-option
                  v-for="item in osVersionList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网络区域" prop="networkArea">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.networkArea"
              >
                <el-option
                  v-for="item in networkAreaList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                  <CommonOptionSpan
                    :date="{
                      left: item.dictLabel,
                      right: item.remark,
                    }"
                  ></CommonOptionSpan>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务系统" prop="businessCode">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.businessCode"
              >
                <el-option
                  v-for="item in businessCodeList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="userCode">
              <choose-dialog
                :selectValue="form.userCode"
                @submitDialog="submitDialog"
                @clearInfo="clearInfo"
              ></choose-dialog>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="MAC地址" prop="macAddress">
              <common-input
                clearable
                v-model="form.macAddress"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="管理地址" prop="managerIp">
              <common-input
                clearable
                :verify="false"
                v-model="form.managerIp"
                placeholder="支持IPV4/IPV6/URL格式"
                :disabled="form.sourceType === 1 && !!initManageIp"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="位置" prop="position">
              <common-input
                clearable
                v-model="form.position"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全级别" prop="passLevel">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.passLevel"
              >
                <el-option
                  v-for="item in passLevelList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重要性" prop="importantLevel">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.importantLevel"
              >
                <el-option
                  v-for="item in importanceList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保密性" prop="secretLevel">
              <el-select
                placeholder="请选择"
                filterable
                clearable
                v-model="form.secretLevel"
              >
                <el-option
                  v-for="item in secretLevelList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <common-add-dept
              ref="commonAddDept"
              :deptListParams="departmentList"
              @getCheckedDeptId="getCheckedDeptId"
              :deptId="form.deptId"
            ></common-add-dept>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="可用性" prop>
              <el-select placeholder="请选择" clearable>
                <el-option label="有负责人" :value="0"> </el-option>
                <el-option label="无负债" :value="1"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完整性" prop="assetsCode">
              <common-input clearable />
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                type="textarea"
                clearable
                placeholder="请输入"
                style="width: 100%"
                v-model="form.remark"
                :maxlength="256"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24"> -->
          <!-- <common-group-title title="策略配置信息"></common-group-title>
          </el-col>
          <el-col :span="12">
            <el-form-item label="协议" prop="agreement">
              <common-input
                clearable
                v-model="form.agreement"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="prot">
              <common-input
                clearable
                v-model="form.prot"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="account">
              <common-input
                clearable
                v-model="form.account"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <common-input
                type="password"
                clearable
                v-model="form.password"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
    </div>
  </common-page>
</template>

<script>
import {
  queryListByTypeCode,
  addAssets,
  editAssets,
  delAssets,
  queryEdit,
  queryTypeCode,
  autoAssetCode,
} from "@/api/analysisCenter/analysis";
2;
import Treeselect from "@riophae/vue-treeselect";
import ChooseDialog from "./components/chooseDialog";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { decode, encode } from "@/utils/aesUtils";
import { validateIPAndURL } from "@/utils/formValidates";
import { param } from "../../../../utils";
export default {
  name: "add",
  components: { Treeselect, ChooseDialog },
  props: {
    title: {
      type: Boolean,
      default: null,
    },
    assetSourceEditId: {
      type: String,
      default: null,
    },
    terrDateName: {
      type: String,
      default: null,
    },
    departmentList: {
      type: Array,
      default: () => [],
    },
    minMenuIds: {
      type: Array,
      default: () => [],
    },
    businessCodeList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      categoryFirstCodeProps: {
        value: "id",
        label: "name",
        children: "children",
        disabled: "disabled",
      },
      allDepList: [],
      factoryList: [],
      networkAreaList: [],
      osVersionList: [],
      importanceList: [],
      secretLevelList: [],
      passLevelList: [],
      loading: false,
      userInfo: null,
      categoryThirdName: null,
      initManageIp: null,
      form: {
        deptName: "",
        importanceLevelName: "",
        businessCodeName: "",
        networkAreaName: "",
        assetSourceId: "",
        assetCode: "",
        assetName: "",
        categoryFirstCode: "",
        categoryParentCode: "",
        categoryThirdCode: [],
        macAddress: "",
        assetItem: "",
        factory: "",
        osVersion: "",
        networkArea: "",
        userCode: "",
        businessCode: "",
        managerIp: "",
        position: "",
        passLevel: null,
        importantLevel: "",
        secretLevel: "",
        remark: "",
        agreement: "",
        prot: "",
        account: "",
        password: "",
        orgCode: "",
        deptId: "",
        sourceType: "",
      },
      rules: {
        assetCode: [
          {
            required: true,
            message: "请输入资产编码",
            trigger: "blur",
          },
        ],
        assetName: [
          { required: true, message: "请输入资产名称", trigger: "blur" },
        ],
        categoryThirdCode: [
          { required: true, message: "请输入资产类型编码", trigger: "blur" },
        ],
        categoryFirstCode: [
          { required: true, message: "请输入资产类型", trigger: "blur" },
        ],
        managerIp: [
          { required: true, message: "请输入管理地址", trigger: "blur" },
          {
            required: true,
            message: "管理地址错误，支持IPV4/IPV6/URL格式",
            validator: validateIPAndURL,
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {},
  computed: {},
  methods: {
    queryAutoAssetCode() {
      autoAssetCode().then((res) => {
        if (res && res.code == "200") {
          this.form.assetCode = res.data;
        } else {
          this.form.assetCode = "";
        }
      });
    },
    getCheckedDeptId(val) {
      this.form.deptId = val;
    },
    handleChange(val) {
      if (val && val.length > 0) {
        if (this.allDepList && this.allDepList.length > 0) {
          this.categoryThirdName = this.allDepList.find(
            (item) => item.id === val[0]
          )?.name;
          this.form.categoryFirstCode = this.allDepList.find(
            (item) => item.id === val[0]
          ).id;
        }

        this.form.categoryParentCode = val && val[1];
        this.form.categoryThirdCode = this.form.categoryThirdCode
          ? this.form.categoryThirdCode[2]
          : [];
      }
    },

    assetsData() {
      if (this.title) {
        return new Promise((resolve, reject) => {
          queryEdit({ assetSourceId: this.assetSourceEditId }).then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              this.form = {};
              this.categoryThirdName = null;
              reject();
            }
          });
        });
      } else {
        this.form = this.$options.data().form;
        this.form.categoryThirdCode = this.minMenuIds;
        this.queryAutoAssetCode();
      }
    },
    goBack() {
      //返回
      this.$emit("close");
    },
    submit() {
      // 保存
      this.importanceList.forEach((item) => {
        if (item.dictValue == this.form.importantLevel) {
          this.form.importanceLevelName = item.dictLabel;
        }
      });
      this.businessCodeList.forEach((item) => {
        if (item.dictValue == this.form.businessCode) {
          this.form.businessCodeName = item.dictLabel;
        }
      });
      this.networkAreaList.forEach((item) => {
        if (item.dictValue == this.form.networkArea) {
          this.form.networkAreaName = item.dictLabel;
        }
      });
      if (this.form.categoryThirdCode instanceof Array) {
        this.form.categoryThirdCode = this.form.categoryThirdCode[2];
      }
      this.form.password = encode(this.form.password);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.title) {
            editAssets(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$emit("submitForm");
                  this.$GlobalSuccessMessage("编辑成功");
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                  this.handleListTips(res);
                }
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            addAssets(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$emit("submitForm");
                  this.$GlobalSuccessMessage("保存成功");
                } else {
                  this.$GlobalErrorConfirm("保存失败", res.msg);
                  this.handleListTips(res);
                }
              })
              .finally(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    queryOsVersionList() {
      //操作系统下拉
      queryListByTypeCode({ dataDictTypeCode: "OPERATING_SYSTEM_" }).then(
        (res) => {
          if (res && res.code === 200) {
            this.osVersionList = res.data;
          } else {
            this.osVersionList = [];
          }
        }
      );
    },
    queryFactoryList() {
      //厂家下拉
      queryListByTypeCode({
        dataDictTypeCode: "SYS_FACTORY_",
      }).then((res) => {
        if (res && res.code === 200) {
          this.factoryList = res.data;
        } else {
          this.factoryList = [];
        }
      });
    },
    queryNetworkAreaList() {
      //网络区域下拉
      queryListByTypeCode({
        dataDictTypeCode: "NETWORK_AREA_",
      }).then((res) => {
        if (res && res.code === 200) {
          this.networkAreaList = res.data;
        } else {
          this.networkAreaList = [];
        }
      });
    },
    queryImportanceList() {
      //重要性
      queryListByTypeCode({
        dataDictTypeCode: "IMPORTANCE_LEVEL_",
      }).then((res) => {
        if (res && res.code === 200) {
          this.importanceList = res.data;
        } else {
          this.importanceList = [];
        }
      });
    },
    querySecretLevelList() {
      //保密性
      queryListByTypeCode({
        dataDictTypeCode: "SECRET_LEVEL_",
      }).then((res) => {
        if (res && res.code === 200) {
          this.secretLevelList = res.data;
        } else {
          this.secretLevelList = [];
        }
      });
    },
    queryPassLevelList() {
      //安全级别
      queryListByTypeCode({
        dataDictTypeCode: "SAFE_LEVEL_",
      }).then((res) => {
        if (res && res.code === 200) {
          this.passLevelList = res.data;
        } else {
          this.passLevelList = [];
        }
      });
    },

    queryTypeCode() {
      //资产类型编码下拉
      return new Promise((resolve, reject) => {
        queryTypeCode().then((res) => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            this.allDepList = [];
            reject();
          }
        });
      });
    },
    allDepListData(data) {
      data.forEach((item) => {
        if (item.children && item.children.length === 0) {
          item.children = null;
        } else {
          this.allDepListData(item.children);
        }
      });
      this.allDepList = data;
    },

    // ------------------选择弹窗组件--------------------

    submitDialog(info, departName) {
      this.form.userCode = info.userName;
      this.form.orgCode = info.deptIds.split(",").pop();
      this.form.deptName = info.deptFullNameArr[0].split("/").pop();
    },

    clearInfo() {
      this.form.userCode = "";
      this.form.orgCode = "";
      this.form.deptName = "";
    },
    //人员列表数据
    // queryUserList(val) {
    //   let params = {
    //     _t: new Date().getTime(),
    //     pageNo: this.querySelect.pageNo,
    //     pageSize: this.querySelect.pageSize
    //   }
    //   queryUserList(params).then(res => {
    //     if (res && res.code === 200) {
    //       this.chooseDialogForm.tableData.unSelectedData.list = res.data.rows.reduce((r, c) => {
    //         r.push({
    //           ...c,
    //           phone: Utils.phoneEncryption(decode(c.phonenumber)),
    //           decodeEmail: Utils.emailEncryption(decode(c.email))
    //         })
    //         return r
    //       }, [])
    //       this.chooseDialogForm.tableData.unSelectedData.total = res.data.total
    //     } else {
    //       this.chooseDialogForm.tableData.unSelectedData.list = []
    //       this.chooseDialogForm.tableData.unSelectedData.total = 0
    //     }
    //   }).catch(err => {
    //     this.chooseDialogForm.tableData.unSelectedData.list = []
    //     this.chooseDialogForm.tableData.unSelectedData.total = 0
    //   })
    // },
    getPromiseAll() {
      Promise.all([this.queryTypeCode(), this.assetsData()]).then((res) => {
        this.allDepListData(res[0].data);
        this.allDepList.forEach((item) => {
          if (item.children != null) {
            item.disabled = false;
            item.children.forEach((t) => {
              if (t.children === null) {
                t.disabled = true;
              } else {
                t.disabled = false;
              }
            });
          } else {
            item.disabled = true;
          }
        });
        if (res[1]) {
          this.form = res[1]?.data;
          this.form.categoryThirdCode = [
            res[1]?.data.categoryFirstCode,
            res[1]?.data.categoryParentCode,
            res[1]?.data.categoryThirdCode,
          ];
          this.form.importantLevel = this.form.importantLevel
            ? this.form.importantLevel.toString()
            : "";
          this.form.secretLevel =
            this.form.secretLevel || this.form.secretLevel === 0
              ? this.form.secretLevel.toString()
              : "";
          this.categoryThirdName = this.allDepList.find(
            (item) => item.id === res[1]?.data.categoryFirstCode
          )?.name;
          this.initManageIp = this.form.managerIp;
        } else {
          if (this.terrDateName) {
            let allCategoryThirdName = "";
            this.allDepList.forEach((item) => {
              if (item.id === this.terrDateName) {
                return (allCategoryThirdName = item.name);
              } else {
                this.categoryThirdName = "";
              }
              if (item.children && item.children instanceof Array) {
                let name = item.name;
                item.children.forEach((t) => {
                  if (t.id === this.terrDateName) {
                    return (allCategoryThirdName = name);
                  } else {
                    this.categoryThirdName = "";
                  }
                });
              }
            });
            this.categoryThirdName = allCategoryThirdName;
            if (!this.title) {
              this.handleChange(this.minMenuIds);
            }
          }
        }
      });
    },
  },

  mounted() {
    this.getPromiseAll();
    this.queryNetworkAreaList();
    this.queryFactoryList();
    this.queryOsVersionList();
    this.queryPassLevelList();
    this.queryImportanceList();
    this.querySecretLevelList();
  },
};
</script>

<style scoped lang="scss">
::v-deep .common-page-content {
  overflow-y: scroll !important;
  .common-page-content {
    width: 50%;
    margin: 0 auto;
  }
}

.el-form-item {
  width: 100%;
  ::v-deep .el-form-item__content {
    width: calc(100% - 110px) !important;
  }
}
</style>
